public class combine {
    public static void main(String[] args) {
        int[] num1 = new int[]{1, 2, 4, 6, 7, 123, 411, 5334, 1414141, 1314141414};
        int[] num2 = new int[]{0, 2, 57, 89, 113, 5623, 6353, 134134};

        System.out.println("数组1：");
        printArray(num1);
        System.out.println("数组2：");
        printArray(num2);

        // 合并两个有序数组
        int[] mergedArray = mergeSortedArrays(num1, num2);

        System.out.println("合并后的有序数组：");
        printArray(mergedArray);
    }

    /**
     * 合并两个有序数组为一个新的有序数组
     */
    public static int[] mergeSortedArrays(int[] arr1, int[] arr2) {
        int length1 = arr1.length;
        int length2 = arr2.length;
        int[] result = new int[length1 + length2];

        // 三个指针：i用于arr1，j用于arr2，k用于result
        int i = 0, j = 0, k = 0;

        // 比较两个数组的元素，将较小的放入结果数组
        while (i < length1 && j < length2) {
            if (arr1[i] <= arr2[j]) {
                result[k++] = arr1[i++];
            } else {
                result[k++] = arr2[j++];
            }
        }

        // 如果arr1还有剩余元素，全部添加到结果数组
        while (i < length1) {
            result[k++] = arr1[i++];
        }

        // 如果arr2还有剩余元素，全部添加到结果数组
        while (j < length2) {
            result[k++] = arr2[j++];
        }

        return result;
    }

    /**
     * 打印数组内容
     */
    public static void printArray(int[] array) {
        for (int i = 0; i < array.length; i++) {
            System.out.print(array[i]);
            if (i < array.length - 1) {
                System.out.print(", ");
            }
            // 每8个元素换一行
            if ((i + 1) % 8 == 0) {
                System.out.println();
            }
        }
        System.out.println("\n");
    }
}